package com.yuanfeng.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.yuanfeng.base.entity.BaseMerchantPlusThaliEntity;
import com.yuanfeng.base.feign.ActivityClient;
import com.yuanfeng.base.feign.UsermsClient;
import com.yuanfeng.base.mapper.BaseMembershipGradeMapper;
import com.yuanfeng.base.mapper.BaseMerchantPlusThaliMapper;
import com.yuanfeng.base.service.BaseMerchantPlusThaliService;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.userms.PlusEquityDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.vo.activity.ActivityRedpacketTemplateVO;
import com.yuanfeng.commoms.vo.base.PlusEquityEntityVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
 */
@Service
public class BaseMerchantPlusThaliServiceImpl extends ServiceImpl<BaseMerchantPlusThaliMapper, BaseMerchantPlusThaliEntity>
    implements BaseMerchantPlusThaliService{

    @Autowired
    private UsermsClient usermsClient;

    @Autowired
    private ActivityClient activityClient;

    @Autowired
    private BaseMembershipGradeMapper baseMembershipGradeMapper;

    @Override
    public ResponseResult queryMerchantPlusThali(Map<String, Object> map) throws IllegalAccessException {
        BaseMerchantPlusThaliEntity entity=this.baseMapper.selectOne(new LambdaQueryWrapper<BaseMerchantPlusThaliEntity>()
                                            .eq(map.containsKey("thaliType"),BaseMerchantPlusThaliEntity::getThaliType,Integer.valueOf(String.valueOf(map.get("thaliType")))));
        Map<String,Object> result= ParseMapUtils.beanToMap(entity);

        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult selectplusthali(Map<String, Object> map) {
        String userInfoStr = RedisUtil.get(YFConfig.YF_PLATFORM_TOKEN_USER + map.get("token"));
        if (null == userInfoStr || userInfoStr.equals("")) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        //判断是否有信息
        Integer thaliType = (Integer) map.get("thaliType");
        BaseMerchantPlusThaliEntity entity=this.baseMapper.selectOne(new LambdaQueryWrapper<BaseMerchantPlusThaliEntity>()
                .eq(map.containsKey("thaliType"),BaseMerchantPlusThaliEntity::getThaliType,Integer.valueOf(String.valueOf(map.get("thaliType")))));
        if (entity != null && entity.getThaliEquity() != null){
            String equity = entity.getThaliEquity();
            String[] split = equity.split(",");
            List<Integer> appIdList = Stream.of(split).map(Integer::parseInt).collect(Collectors.toList());
            entity.setThaliEquityList(appIdList);
            Object data = usermsClient.selectplusequitys(appIdList).getData();
            List<PlusEquityDTO> selectplusequitys = JSONObject.parseArray(JSON.toJSONString(data),PlusEquityDTO.class);
            if (selectplusequitys != null && selectplusequitys.size() > 0){
                for (PlusEquityDTO plusEquityEntity : selectplusequitys) {
                    //获取红包模板
                    if (plusEquityEntity.getEquityType() == 2 || plusEquityEntity.getEquityType() == 3){
                        String equityValue = plusEquityEntity.getEquityValue();
                        String[] split1 = equityValue.split(",");
                        List<Integer> redIdList = Stream.of(split1).map(Integer::parseInt).collect(Collectors.toList());
                        //查询红包模板
                        Map<String, Object> actMap = new HashMap<>();
                        actMap.put("id",redIdList);
                        ResponseResult result = activityClient.redpacketTemplateList(map);
                        List<ActivityRedpacketTemplateVO> redTemplateEntities= (List<ActivityRedpacketTemplateVO>) result.getData();

                        plusEquityEntity.setRedList(redTemplateEntities);
                    }
                    if (plusEquityEntity.getEquityType() == 1){
                        BigDecimal multiply = new BigDecimal(plusEquityEntity.getEquityValue()).multiply(new BigDecimal(10));
                        plusEquityEntity.setEquityValue(multiply.toString());
                    }
                }
            }
            entity.setPlusEquitys(selectplusequitys);
        }
        return ResponseResult.success(entity);
    }

    @Override
    public ResponseResult renewplusthali(Map<String, Object> map) {
//        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(String.valueOf(map.get("token")));
//        if (userInfoVO == null) {
//            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
//        }
        //判断是否有信息
        String thaliType = map.get("plusOrder").toString();
        BaseMerchantPlusThaliEntity entity=this.baseMapper.selectthalitype1(thaliType);
        if (entity != null && entity.getThaliEquity() != null){
            String equity = entity.getThaliEquity();
            String[] split = equity.split(",");
            List<Integer> appIdList = Stream.of(split).map(Integer::parseInt).collect(Collectors.toList());
            entity.setThaliEquityList(appIdList);

            String data = JSON.toJSONString(usermsClient.selectplusequitys(appIdList).getData());
            List<PlusEquityDTO> selectplusequitys = JSONObject.parseArray(data, PlusEquityDTO.class);
            if (selectplusequitys != null && selectplusequitys.size() > 0){
                for (PlusEquityDTO plusEquityEntity : selectplusequitys) {
                    //获取红包模板
                    if (plusEquityEntity.getEquityType() == 2 || plusEquityEntity.getEquityType() == 3){
                        String equityValue = plusEquityEntity.getEquityValue();
                        String[] split1 = equityValue.split(",");
                        List<Integer> redIdList = Stream.of(split1).map(Integer::parseInt).collect(Collectors.toList());
                        //查询红包模板
                        Map<String, Object> actMap = new HashMap<>();
                        actMap.put("id",redIdList);
                        ResponseResult result = activityClient.redpacketTemplateList(actMap);
                        List<ActivityRedpacketTemplateVO> redTemplateEntities= (List<ActivityRedpacketTemplateVO>) result.getData();

                        plusEquityEntity.setRedList(redTemplateEntities);
                    }
                    if (plusEquityEntity.getEquityType() == 1){
                        BigDecimal multiply = new BigDecimal(plusEquityEntity.getEquityValue()).multiply(new BigDecimal(10));
                        plusEquityEntity.setEquityValue(multiply.toString());
                    }
                }
            }
            entity.setPlusEquitys(selectplusequitys);
        }
        return ResponseResult.success(entity);
    }

    @Override
    public ResponseResult setplusthali(Map<String, Object> map) {
        String userInfoStr = RedisUtil.get(YFConfig.YF_PLATFORM_TOKEN_USER + map.get("token"));
        if (null == userInfoStr || userInfoStr.equals("")) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        //判断是否有信息
        BaseMerchantPlusThaliEntity entity=this.baseMapper.selectOne(new LambdaQueryWrapper<BaseMerchantPlusThaliEntity>()
                .eq(map.containsKey("thaliType"),BaseMerchantPlusThaliEntity::getThaliType,Integer.valueOf(String.valueOf(map.get("thaliType")))));
        Integer integer = null;
        if (map.get("thaliEquityList") != null){
            List list = (List) map.get("thaliEquityList");
            String s = Joiner.on(",").join(list);
            map.put("thaliEquity",s);
        }
        if (entity == null){
            integer = this.baseMapper.insertplusthali(map);
        }else{
            integer =  this.baseMapper.updateplusthali(map);
        }
        if (integer > 0){
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        }
        return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
    }

    @Override
    public ResponseResult selectplusdiscount() {
        //查询套餐表
        List<BaseMerchantPlusThaliEntity> plusThaliEntities = this.baseMapper.selectList(new LambdaQueryWrapper<BaseMerchantPlusThaliEntity>()
                                                  .eq(BaseMerchantPlusThaliEntity::getThaliStatus, CommonType.commonStatus.YES.getCode()));
        //查询平台最低会员折扣
        String memberdiscount = baseMembershipGradeMapper.selectmemberdiscount();
        BigDecimal bigDecimal = new BigDecimal(memberdiscount);
        ArrayList<Object> returnList = new ArrayList<>();
        if (plusThaliEntities != null && plusThaliEntities.size() > 0){
            for (BaseMerchantPlusThaliEntity plusThaliEntity : plusThaliEntities) {

                String thaliEquity = plusThaliEntity.getThaliEquity();
                String[] split = thaliEquity.split(",");
                List<Integer> appIdList = Stream.of(split).map(Integer::parseInt).collect(Collectors.toList());
                plusThaliEntity.setThaliEquityList(appIdList);

                List<PlusEquityEntityVO> selectplusequitys = this.baseMapper.selectplusequitys(appIdList);
                if (selectplusequitys != null && selectplusequitys.size() > 0){
                    for (PlusEquityEntityVO selectplusequity : selectplusequitys) {
                        if (selectplusequity.getEquityType() == 1){
                            HashMap<Object, Object> map = new HashMap<>();
                            String equityValue = selectplusequity.getEquityValue();
                            BigDecimal bigDecimal1 = new BigDecimal(equityValue);
                            BigDecimal subtract = bigDecimal.subtract(bigDecimal1);

                            BigDecimal multiply = bigDecimal1.multiply(new BigDecimal(10));//用于前端展示

                            map.put("thaliType",plusThaliEntity.getThaliType());
                            map.put("equityValue",multiply.toString());
                            map.put("memberDiscount",subtract);
                            returnList.add(map);
                        }
                    }
                }
            }
        }
        return ResponseResult.success(returnList);
    }
}




